package ac.svn.accesscontrol.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import ac.svn.accesscontrol.store.Dictionary;

public class ConfigFileHandler implements IConfigProvider {


    public ConfigFileHandler()
    {
    }
    /* (non-Javadoc)
     * @see ac.svn.accesscontrol.io.IConfigReader#readConfiguration(java.lang.String, java.lang.Object)
     */
    @Override
    public boolean readConfiguration(String fileName,Object dictionaryObject)
    {
	boolean readStatus = true;
	File file = new  File(fileName);
	try
	{
	    FileInputStream fileInputStream = new FileInputStream(file);
	    ObjectInputStream ois = new ObjectInputStream(fileInputStream);
	    Object object = ois.readObject();
	    if(null !=  object)
	    {
		Dictionary cur = (Dictionary) dictionaryObject;
		Dictionary read = (Dictionary) object;
		cur.clone(read);
		read = null;
	    }
	    ois.close();
	    fileInputStream.close();
	}
	catch(FileNotFoundException fe)
	{
	    try 
	    {
		file.createNewFile();
		readConfiguration(fileName, dictionaryObject);
	    }
	    catch (IOException e) 
	    {
		readStatus = false;
		e.printStackTrace();
	    }
	} 
	catch (IOException e) 
	{
	    readStatus = false;
	    e.printStackTrace();
	}
	catch (ClassNotFoundException e) 
	{
	    readStatus = false;
	    e.printStackTrace();
	}

	return readStatus;
    }


    /* (non-Javadoc)
     * @see ac.svn.accesscontrol.io.IConfigReader#saveConfiguration(java.lang.String, java.lang.Object)
     */
    @Override
    public boolean saveConfiguration(String fileName, Object dictionaryObject)
    {
	boolean writeStatus = true;
	File file = new File(fileName);
	try
	{
	    FileOutputStream fileOutputStream = new FileOutputStream(file); 
	    ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
	    oos.writeObject(dictionaryObject);
	    oos.close();
	    fileOutputStream.close();
	    System.err.println("File saved!");
	}
	catch(FileNotFoundException fe)
	{
	    try
	    {
		file.createNewFile();
	    }
	    catch(IOException ioe)
	    {
		writeStatus = false;
		ioe.printStackTrace();
	    }
	}
	catch (IOException e) 
	{
	    writeStatus = false;
	    e.printStackTrace();
	}
	return writeStatus;
    }
}
